<template>
    <div>
        <div class="video-container">
            <div class="title flex justify-between">
                <div class="left">
                    <el-button type="primary" size="small" round>关注</el-button>
                </div>
                <div class="right">
                    在线观众 <el-input-number size="small" v-model="onlineNum"></el-input-number>
                </div>
            </div>
            <video class="video" ref="videoRef"></video>
            <div class="barrage-box" id="barrage-box"  >
                <ul class="comment-list" ref="commentList">
                    <li v-for="(item, index) in comments" :key="index" class="comment-item">
                        {{ item.user_grade_level }} {{ item.userNick }} : {{ item.chat_msg }}
                    </li>
                </ul>
            </div>
            <el-row justify="space-between">
                <el-col :span="18">
                    <el-input size="small" v-model="message"></el-input>
                </el-col>
                <el-col :span="4">
                    <el-button size="small" @click="sendMessage">发送</el-button>
                </el-col>
            </el-row>
        </div>
    </div>
    <!-- <el-form-item>
        <FieldControlCom @updateBarrage="getBarrage"></FieldControlCom>
    </el-form-item> -->
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { ipcApiRoute } from '@/api/main';
import { ipc } from '@/utils/ipcRenderer';
import { ElMessage } from 'element-plus'
import FieldControlCom from '@/components/FieldControlCom/index.vue'

const props = defineProps({
    messageList: {
        type: Array,
        required: true,
        default: () => []
    }
});

const videoRef = ref()
const selectedSourceId = ref("")
const comments = ref([])
const message = ref("")
const onlineNum = ref(1)

const emit = defineEmits(['updateBarrage'])

watch(
    () => props.messageList,
    () => {
        nextTick(() => {
            comments.value = [...props.messageList]
            console.log("comments.value------", comments.value)
            scrollToBottom()
        });
    },
    { deep: true }
);
const getBarrage = (val) => {
    console.log('[getBarrage] val:', val);
    comments.value = [...val]
}

const sendMessage = () => {
    if (message.value) {

        emit('updateBarrage', {
            chat_msg: message.value,
            userNick: '游客',
            user_grade_level: comments.value.length + 1
        })
        message.value = ''
    }else{
        ElMessage.error('请输入发送内容')
    }
}

// 有新消息对话框自动滚动到最新消息处
const scrollToBottom = () => {
    const el = document.getElementById("barrage-box")
    if (el) {
        setTimeout(() => {
            el.scrollTop = el.scrollHeight;
        }, 0)
    }
}
const getDeskApp = () => {
    ipc.invoke(ipcApiRoute.getScreenApp).then(res => {
        console.log('[getDeskApp] rst:', res);
        const targetApp = res.find(item => item.name === 'Living')
        selectedSourceId.value = targetApp?.id || ''

        if (selectedSourceId.value) {
            startCapture()
        } else {
            ElMessage.error('数字人播放器没有启动')
            console.log('[getDeskApp] 没有找到应用');
        }
    })
}

const startCapture = async () => {
    const constraints = {
        audio: false,
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
                chromeMediaSourceId: selectedSourceId.value,
            }
        }
    };
    try {
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        // 将stream绑定到video标签
        const video = videoRef.value
        video.srcObject = stream
        video.onloadedmetadata = video.play
    } catch (error) {
        console.error('捕获失败:', error);
    }
}

defineExpose({
    getDeskApp
})
</script>

<style lang="less" scoped>
.video-container {
    position: relative;

    .title {
        position: absolute;
        top:5px;
        left:0;
        right:0;
        margin: auto;
        font-size: 12px;
        z-index: 999
    }

    .video{
        width: 300px;
    }
    .barrage-box {
        position: absolute;
        bottom: 0;
        left: 10px;
        height: 200px;
        overflow-y: auto;

        .comment-list {
            list-style-type: none;
            padding: 0;
            margin: 0;
            font-size: 12px;
        }

        .comment-item {
            padding: 5px 0;
            text-align: left;
        }
    }

    .barrage-box::-webkit-scrollbar {
        display: none;
    }
}
</style>